import pygame
from enum import auto, Enum


class EventId(Enum):
    # Entity Events
    player_attack_mob = auto()
    mob_attack_player = auto()
    mob_attack_mob = auto()

    # Player Events
    player_move = auto()

    # Item Events
    pickup_item = auto()
    drop_item = auto()
    use_item = auto()

    # Armor Events
    equip_armor = auto()
    unequip_armor = auto()

    # Game Events
    toggle_game_pause = auto()
    game_start = auto()
    game_quit = auto()
    dialog_end = auto()

    # Keyboard & Mouse Events
    mouse_button_up = auto()
    mouse_button_down = auto()
    key_up = auto()
    key_down = auto()

    # UI Events
    button_clicked = auto()

    # main menu
    load_game = auto()
    open_options = auto()


class _EventBus:
    """ Handle all events """

    def __init__(self):
        self.__eventPool = {}

    def register(self, eventId: EventId, callback):
        """ Add callback function to an event. """

        if eventId in self.__eventPool:
            self.__eventPool[eventId].append(callback)
        else:
            self.__eventPool[eventId] = [callback]

    def triggerEvent(self, eventId: EventId, *args, **kwargs):
        callbacks = self.__eventPool.get(eventId)
        if callbacks is not None:
            for callback in callbacks:
                callback(*args, **kwargs)


# detect and trigger events
def event_decter():
    for event in pygame.event.get():
        match event.type:

            case pygame.MOUSEBUTTONDOWN:
                Eventbus.triggerEvent(EventId.mouse_button_down,
                                      event.pos,
                                      event.button)

            case pygame.MOUSEBUTTONUP:
                Eventbus.triggerEvent(EventId.mouse_button_up,
                                      event.pos,
                                      event.button)
            case pygame.KEYDOWN:
                Eventbus.triggerEvent(EventId.key_down, event.key)

            case pygame.KEYUP:
                Eventbus.triggerEvent(EventId.key_up, event.key)

            case pygame.QUIT:
                Eventbus.triggerEvent(EventId.game_quit)
# singleton
Eventbus = _EventBus()
